import React from 'react';
import moment from 'moment';
import _ from 'lodash';
import {
    Table as TableX,
    Modal as ModalX,
    Button as ButtonX,
    Spin as SpinX,
    Input,
    Switch,
    Select,
} from 'antd';
import {responseWidth} from '../global';

require('./ui.less');

/*
require('./../libs/pinyinUtil');

export const pinyin = (str, mode) => {
    if (!str) {
        return '';
    }
    const pinyinUtil = window.pinyinUtil;
    let pys = pinyinUtil.getPinyin(str, ' ', false).split(' ');
    pys = _.filter(pys, i => i !== null && i !== '');
    switch (mode) {
        case 1:
            break;
        case 2:
            pys = pys.map(i => i[0]).join('');
            break;
        default:
            const firstChars = pys.map(i => i[0]);
            if (!_.isEqual(pys, firstChars)) pys = _.concat(firstChars, ['|'], pys);
            break;
    }
    return pys.join('');
};*/

/**
 * 便于统一实现Button行为如粒度的权限控制
 * @param props
 * @constructor
 */
export const Button = props => (
    <ButtonX {...props} className={props.className || 'btnNormal'}>{props.children}</ButtonX>
);

/**
 * 便于统一实现Model行为
 * @param props
 * @constructor
 */
export const Modal = props => (
    <ModalX
        width={responseWidth()}
        maskClosable={false}
        {...props}
    >
        {props.children}
    </ModalX>
);

export const YesNo = (props) => (
    <Switch size="small" {...props} />
);

/**
 * 数据表格
 * @param props
 * @constructor
 */
export const Table = props => {
    const {columns, className = 'tableNormal'} = props;
    const status = _.find(columns, ['title', '状态']);
    const operator = _.find(columns, ['title', '操作']);
    if (status) {
        status.className = 'center';
        status.width = 64;
    }
    if (operator) {
        operator.className = 'center';
        operator.width = 128;
    }
    return (
        <TableX
            className={className}
            rowKey="id"
            bordered
            rowClassName={(rec, idx) => ((idx % 2) ? 'odd-row' : '')}
            {...props}
        />
    );
};
/*
 树形Table
 */
/**
 * 扁平 --> 树形
 * @param data 原始扁平数据
 * @param node 调用方法时不用填写，内部递归时使用
 * @param i 同上
 * @param sid 自身id键名，默认id
 * @param pid 父级id键名，默认pid
 */
export const flat2Tree = ({data, node = null, i, sid = 'id', pid = 'pid'}) => {
    if (!node) {
        _.forEach(data, (v, i) => {
            if (v && v[pid]) {
                flat2Tree({
                    data,
                    node: v,
                    i
                });
            }
        });
    } else {
        _.forEach(data, (v) => {
            if (v) {
                if (v[sid] === node[pid]) {
                    if (!v.children) {
                        v.children = [];
                    }
                    v.children.push(node);
                } else if (v.children) {
                    flat2Tree({
                        data: v.children,
                        node
                    });
                }
            }
        });
        if (i !== undefined) {
            data[i] = null;
        }
    }
    return _.compact(data);
};
export const TableTree = (props) => {
    const {data = [], isAsync, onExpand} = props;
    if (isAsync && !_.isFunction(onExpand)) {
        throw new Error('如果你需要异步加载子集，请定义 onExpand 监听方法， 此时可以发送查询子集数据的请求！！');
    }
    const fbData = flat2Tree({data: _.cloneDeep(data)});
    return (
        <Table
            dataSource={fbData}
            {...props}
        />
    );
};

function setColKey(col) {
    if (!col.key && col.dataIndex) {
        col.key = col.dataIndex;
    }
}

export function setColumnKeys(columns) {
    columns.forEach(col => {
        setColKey(col);
        if (col.children) {
            setColumnKeys(col.children);
        }
    });
    return columns;
}

/**
 * 分页,便于统一定制分页样式
 * @param props
 * @returns {XML}
 * @constructor
 */
export const Pagination = (props = {}) => {
    const {name, format, change, total} = props;
    if (total <= 10) { // 和分页大小的最小值
        return false;
    }
    let {pageSize} = props;

    const template = _.template(format || '共 {{total}} 条{{name}}');
    const handleChange = (page, size) => {
        if (!change) {
            return;
        }
        if (size !== undefined && size !== pageSize) {
            page = 1;
            pageSize = size;
        }
        change({
            pageSize,
            page
        });
    };
    const pageSizeOptions = ['10', '20', '30', '50', '100', '150'];
    return {
        onChange: handleChange,
        onShowSizeChange: handleChange,
        showTotal: (total, range) => {
            return template({
                ...props,
                total,
                range,
                name: name || '数据'
            });
        },
        pageSize,
        showSizeChanger: true,
        pageSizeOptions,
        ...props
    };
};

/**
 * 加载中控件
 * @param props
 * @constructor
 */
export const Spin = (props) => (
    <SpinX
        delay={300}
        {...props}
        spinning={!!props.spinning}
    >
        {props.children}
    </SpinX>
);


/**
 *获取树形数据
 * @param data
 * @param sid 当前已选择数据id
 * @param pid //父级数据id
 * @returns {Array}
 */
export function getTree(data = [], sid, pid = null) {
    const children = [];
    for (const i in data) {
        const node = data[i];
        if (((!pid && !node.pid) || node.pid === pid) && node.id !== sid) {
            children.push({
                key: node.id,
                value: node.id + '',
                label: node.name,
                children: getTree(data, sid, node.id),
                ...node
            });
        }
    }
    return children;
}

export function getCasTree(data = [], sid, pid = null) {
    const children = [];
    for (const i in data) {
        const node = data[i];
        if (((!pid && !node.pid) || node.pid === pid) && node.id !== sid) {
            children.push({
                key: node.id,
                value: node.name,
                label: node.name,
                children: getCasTree(data, sid, node.id),
                ...node
            });
        }
    }
    return children;
}

/**
 * 获取select初始值
 * @param data
 */
export const selectInitialValue = (data) => `${_.get(data, '[0].id', '')}`;

/**
 * 生成select options
 * @param data
 */
export const selectOptions = (data) => {
    return _.reduce(data, (res, v) => {
        const {id, name} = v;
        res.push(<Select.Option key={id} value={`${id}`} data={v}>{name}</Select.Option>);
        return res;
    }, []);
};

/**
 * select 属性
 */
export const selectProps = {
    notFoundContent: '未找到,请重试',
    showSearch: true,
    dropdownMatchSelectWidth: false,
    filterOption(inputValue, {props}){
        const {code, name, nameJp} = props.data;
        return (code && code.indexOf(inputValue) >= 0)
            || (name && name.indexOf(inputValue) >= 0)
            || (nameJp && nameJp.indexOf(inputValue) >= 0);
    },
};
export const Search = ({className = 'searchNormal', ...args}) => (
    <Input.Search {...args} className={className}/>
);
export const SearchInput = require('./searchInput');

/**
 * 创建图标(支持fa图标,如 fa fa-xxx 和iconfont图标 如 iconfont icon-xxx)
 * @param ico
 * @returns {*}
 */
export const createIcon = (ico) => {
    ico = ico && _.trim(ico);
    if (ico && (_.startsWith(ico, 'icon') || _.startsWith(ico, 'fa'))) {
        return <i className={ico} style={{marginRight: '5px'}}/>;
    }
    return '';
};

/**
 * 时间格式化
 * @param date
 * @returns {string}
 */
export function dateFull(date) {
    if (!date) {
        return '';
    }
    return moment(date).format('YYYY-MM-DD HH:mm:ss');
}

/**
 * 短时间格式化
 * @param date
 * @param format
 * @returns {string}
 */
export function dateShort(date) {
    if (!date) {
        return '';
    }
    return moment(date).format('YYYY-MM-DD');
}
